package com.egao.common.manage.bigView.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.RankingVO;
import com.egao.common.module.company.entity.Position;
import com.egao.common.module.company.entity.Preach;
import com.egao.common.module.company.service.PositionService;
import com.egao.common.module.company.service.PreachService;
import com.egao.common.module.student.constants.StudentSignConstants;
import com.egao.common.module.student.constants.StudentSignRecordConstants;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.entity.StudentSign;
import com.egao.common.module.student.entity.StudentSignRecord;
import com.egao.common.module.student.service.StudentService;
import com.egao.common.module.student.service.StudentSignRecordService;
import com.egao.common.module.student.service.StudentSignService;
import com.egao.common.module.system.entity.Year;
import com.egao.common.module.system.service.YearService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lym
 * @date 2024/8/15 9:29
 */
@Api(tags = "大屏 市场板块")
@RestController
@RequestMapping("${api}")
public class BigViewController extends BaseController {

    @Resource
    private YearService yearService;
    @Resource
    private PreachService preachService;
    @Resource
    private PositionService positionService;
    @Resource
    private StudentService studentService;
    @Resource
    private StudentSignService studentSignService;
    @Resource
    private StudentSignRecordService studentSignRecordService;

    @ApiOperation(value = "毕业年份")
    @GetMapping("/big-view/year")
    public JsonResult year() {
        Year year = yearService.getYear();
        List<Year> yearList = yearService.list(new LambdaQueryWrapper<Year>().orderByAsc(Year::getId));

        Map<String, Object> map = new HashMap<>(2);
        map.put("year", year.getId());
        map.put("yearList", yearList);
        return JsonResult.ok().setData(map);
    }

    @ApiOperation(value = "市场板块统计")
    @GetMapping("/big-view/market")
    public JsonResult statistics(Integer year) {
        // 年份区间
        String startDateStr = StrUtil.format("{}-01-01 00:00:00", year);
        String endDateStr = StrUtil.format("{}-12-31 23:59:59", year);
        Date startDate = DateUtil.parse(startDateStr);
        Date endDate = DateUtil.parse(endDateStr);

        // 宣讲会
        List<Preach> preachList = preachService.effectiveList(startDate, endDate);
        // 宣讲会举办次数
        Integer preachCount = preachList.size();
        // 宣讲会参与学生个数 目前没有这个数据
        Integer preachStudentCount = 0;
        // 宣讲会招聘岗位个数 岗位*招聘人数
        Integer preachPositionCount = 0;
        String positionIds = preachList.stream().map(Preach::getPositionIds).collect(Collectors.joining(","));
        if (!StrUtil.isBlank(positionIds)) {
            List<Position> positionList = positionService.list(new LambdaQueryWrapper<Position>()
                    .in(Position::getId, positionIds)
            );
            for (Position item : positionList) {
                preachPositionCount += NumberUtil.isInteger(item.getNumber()) ? Integer.parseInt(item.getNumber()) : 0;
            }
        }
        // 今日宣讲会举办次数
        Date startToday = DateUtil.beginOfDay(new Date());
        Date endToday = DateUtil.endOfDay(new Date());
        long preachTodayCount = preachList.stream().filter(d -> d.getHoldTime().getTime() >= startToday.getTime() && d.getHoldTime().getTime() <= endToday.getTime()).count();
        Map<String, Object> preachMap = new HashMap<>(4);
        preachMap.put("preachCount", preachCount);
        preachMap.put("preachStudentCount", preachStudentCount);
        preachMap.put("preachPositionCount", preachPositionCount);
        preachMap.put("preachTodayCount", preachTodayCount);

        // 双选会
        // 双选会场次
        Integer mutualCount = 30;
        // 双选会参会单位个数
        Integer mutualCompanyCount = 200;
        // 双选会参与学生个数
        Integer mutualStudentCount = 1500;
        // 双选会岗位个数
        Integer mutualPositionCount = 600;
        Map<String, Object> mutualMap = new HashMap<>(4);
        mutualMap.put("mutualCount", mutualCount);
        mutualMap.put("mutualCompanyCount", mutualCompanyCount);
        mutualMap.put("mutualStudentCount", mutualStudentCount);
        mutualMap.put("mutualPositionCount", mutualPositionCount);

        // 选调专栏
        // 选调信息个数
        Integer chooseCount = 50;
        // 选调央选个数
        Integer chooseCenterCount = 20;
        // 选调省调个数
        Integer chooseProvinceCount = 30;
        Map<String, Object> chooseMap = new HashMap<>(3);
        chooseMap.put("chooseCount", chooseCount);
        chooseMap.put("chooseCenterCount", chooseCenterCount);
        chooseMap.put("chooseProvinceCount", chooseProvinceCount);

        Map<String, Object> map = new HashMap<>(3);
        map.put("preach", preachMap);
        map.put("mutual", mutualMap);
        map.put("choose", chooseMap);

        return JsonResult.ok().setData(map);
    }

    @ApiOperation(value = "毕业去向饼图数据源")
    @GetMapping("/big-view/student-sign-pie")
    public JsonResult studentSignPie(Integer year) {
        // 查询最新毕业去向就业率合计
        List<StudentSignRecord> list = studentSignRecordService.getStudentSignRateRecord(year, null, null);

        Map<String, Object> allMap = new HashMap<>(4);
        Map<String, Object> bkMap = new HashMap<>(4);
        Map<String, Object> ssMap = new HashMap<>(4);
        Map<String, Object> bsMap = new HashMap<>(4);

        for (StudentSignRecord item : list) {
            if (!"合计".equals(item.getTitle())) {
                continue;
            }
            if (StudentSignRecordConstants.XL_ALL.equals(item.getXl())) {
                allMap.put("title", "总生源 " + item.getCount());
                allMap.put("totalCount", item.getTotalCount());
                allMap.put("totalRate", item.getTotalRate());
                allMap.put("daiCount", item.getDaiCount());
            }
            if (StudentSignRecordConstants.XL_BK.equals(item.getXl())) {
                bkMap.put("title", "本科生源 " + item.getCount());
                bkMap.put("totalCount", item.getTotalCount());
                bkMap.put("totalRate", item.getTotalRate());
                bkMap.put("daiCount", item.getDaiCount());
            }
            if (StudentSignRecordConstants.XL_SS.equals(item.getXl())) {
                ssMap.put("title", "硕士生源 " + item.getCount());
                ssMap.put("totalCount", item.getTotalCount());
                ssMap.put("totalRate", item.getTotalRate());
                ssMap.put("daiCount", item.getDaiCount());
            }
            if (StudentSignRecordConstants.XL_BS.equals(item.getXl())) {
                bsMap.put("title", "博士生源 " + item.getCount());
                bsMap.put("totalCount", item.getTotalCount());
                bsMap.put("totalRate", item.getTotalRate());
                bsMap.put("daiCount", item.getDaiCount());
            }
        }

        Map<String, Object> map = new HashMap<>(4);
        map.put("all", allMap);
        map.put("bk", bkMap);
        map.put("ss", ssMap);
        map.put("bs", bsMap);

        return JsonResult.ok().setData(map);
    }

    @ApiOperation(value = "管理板块")
    @GetMapping("/big-view/manage")
    public JsonResult manage(Integer year) {
        List<Student> list = studentService.list(new LambdaQueryWrapper<Student>()
                .eq(Student::getYearId, year)
        );

        // 困难生
        List<Student> knsList = list.stream().filter(d -> !"0".equals(d.getKnslb())).collect(Collectors.toList());
        List<Integer> knsIds = knsList.stream().map(Student::getId).collect(Collectors.toList());
        // 困难生人数
        Integer knsCount = knsList.size();
        // 困难生建档人数
        Integer knsJdCount = 0;
        // 困难生意向求职人数
        long knsQzCount = knsList.stream().filter(d -> !StrUtil.isBlank(d.getInten()) && d.getInten().contains("求职")).count();
        // 困难生已签约人数
        Integer knsQyCount = 0;
        if (knsIds.size() > 0) {
            knsQyCount = studentSignService.count(new LambdaQueryWrapper<StudentSign>()
                    .eq(StudentSign::getState, StudentSignConstants.STATE_VALID)
                    .eq(StudentSign::getSignState, StudentSignConstants.SIGN_STATE_SCHOOL_PASS)
                    .eq(StudentSign::getDispatchState, StudentSignConstants.DISPATCH_STATE_SCHOOL_PASS)
                    .eq(StudentSign::getSignCategory, StudentSignConstants.SIGN_CATEGORY_XYJY)
                    .in(StudentSign::getStudentId, knsIds)
            );
        }
        // 困难生意向升学人数
        long knsSxCount = knsList.stream().filter(d -> !StrUtil.isBlank(d.getInten()) &&
                (d.getInten().contains("升学(出国出境)") || d.getInten().contains("考研") || d.getInten().contains("考博"))).count();
        Map<String, Object> knsMap = new HashMap<>();
        knsMap.put("knsCount", knsCount);
        knsMap.put("knsJdCount", knsJdCount);
        knsMap.put("knsQzCount", knsQzCount);
        knsMap.put("knsQyCount", knsQyCount);
        knsMap.put("knsSxCount", knsSxCount);


        // 民族学生
        List<Student> mzList = list.stream().filter(d -> !"01".equals(d.getMz())).collect(Collectors.toList());
        List<Integer> mzIds = mzList.stream().map(Student::getId).collect(Collectors.toList());
        // 民族学生人数
        Integer mzCount = mzList.size();
        // 民族学生求职人数
        long mzQzCount = mzList.stream().filter(d -> !StrUtil.isBlank(d.getInten()) && d.getInten().contains("求职")).count();
        // 民族学生签约人数
        Integer mzQyCount = 0;
        if (mzIds.size() > 0) {
            mzQyCount = studentSignService.count(new LambdaQueryWrapper<StudentSign>()
                    .eq(StudentSign::getState, StudentSignConstants.STATE_VALID)
                    .eq(StudentSign::getSignState, StudentSignConstants.SIGN_STATE_SCHOOL_PASS)
                    .eq(StudentSign::getDispatchState, StudentSignConstants.DISPATCH_STATE_SCHOOL_PASS)
                    .eq(StudentSign::getSignCategory, StudentSignConstants.SIGN_CATEGORY_XYJY)
                    .in(StudentSign::getStudentId, mzIds)
            );
        }
        // 民族学生升学人数
        long mzSxCount = mzList.stream().filter(d -> !StrUtil.isBlank(d.getInten()) &&
                (d.getInten().contains("升学(出国出境)") || d.getInten().contains("考研") || d.getInten().contains("考博"))).count();
        Map<String, Object> mzMap = new HashMap<>();
        mzMap.put("mzCount", mzCount);
        mzMap.put("mzQzCount", mzQzCount);
        mzMap.put("mzQyCount", mzQyCount);
        mzMap.put("mzSxCount", mzSxCount);

        // 单位邀约人数
        Integer companyYyCount = 0;
        // 单位邀约待审核人数
        long companyYyDshCount = 0;
        List<Integer> studentIds = list.stream().map(Student::getId).collect(Collectors.toList());
        if (studentIds.size() > 0) {
            List<StudentSign> studentSignList = studentSignService.list(new LambdaQueryWrapper<StudentSign>()
                    .eq(StudentSign::getState, StudentSignConstants.STATE_VALID)
                    .eq(StudentSign::getSignCategory, StudentSignConstants.SIGN_CATEGORY_XYJY)
                    .eq(StudentSign::getSignWay, StudentSignConstants.SIGN_WAY_COMPANY)
                    .in(StudentSign::getStudentId, studentIds)
            );

            companyYyCount = studentSignList.size();
            companyYyDshCount = studentSignList.stream().filter(d -> StudentSignConstants.SIGN_STATE_STUDENT_AGREED.equals(d.getSignState())).count();
        }
        Map<String, Object> companyYyMap = new HashMap<>();
        companyYyMap.put("companyYyCount", companyYyCount);
        companyYyMap.put("companyYyDshCount", companyYyDshCount);

        Map<String, Object> map = new HashMap<>();
        map.put("kns", knsMap);
        map.put("mz", mzMap);
        map.put("companyYy", companyYyMap);

        return JsonResult.ok().setData(map);
    }

    @ApiOperation(value = "指导板块")
    @GetMapping("/big-view/guidance")
    public JsonResult guidance(Integer year) {
        List<Student> list = studentService.list(new LambdaQueryWrapper<Student>()
                .eq(Student::getYearId, year)
        );

        // 意向地区
        String addressStr = list.stream().map(Student::getIntenAddress).filter(intenAddress -> !StrUtil.isBlank(intenAddress)).collect(Collectors.joining(","));
        String[] addressArr = addressStr.split(",");
        List<RankingVO> addressAllList = new ArrayList<>();
        for (String address : addressArr) {
            long size = addressAllList.stream().filter(d -> d.getName().equals(address)).count();
            if (size > 0) {
                continue;
            }
            long count = Arrays.stream(addressArr).filter(d -> d.equals(address)).count();
            addressAllList.add(new RankingVO(address, (int) count));
        }
        addressAllList.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));
        List<RankingVO> addressList = addressAllList.subList(0, Math.min(addressAllList.size(), 3));

        // 意向行业
        String industryStr = list.stream().map(Student::getIntenIndustry).filter(getIntenIndustry -> !StrUtil.isBlank(getIntenIndustry)).collect(Collectors.joining(","));
        String[] industryArr = industryStr.split(",");
        List<RankingVO> industryAllList = new ArrayList<>();
        for (String industry : industryArr) {
            long size = industryAllList.stream().filter(d -> d.getName().equals(industry)).count();
            if (size > 0) {
                continue;
            }
            long count = Arrays.stream(industryArr).filter(d -> d.equals(industry)).count();
            industryAllList.add(new RankingVO(industry, (int) count));
        }
        industryAllList.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));
        List<RankingVO> industryList = industryAllList.subList(0, Math.min(industryAllList.size(), 10));

        // 意向岗位
        String nameStr = list.stream().map(Student::getIntenName).filter(getIntenName -> !StrUtil.isBlank(getIntenName)).collect(Collectors.joining(","));
        String[] nameArr = nameStr.split(",");
        List<RankingVO> nameAllList = new ArrayList<>();
        for (String name : nameArr) {
            long size = nameAllList.stream().filter(d -> d.getName().equals(name)).count();
            if (size > 0) {
                continue;
            }
            long count = Arrays.stream(nameArr).filter(d -> d.equals(name)).count();
            nameAllList.add(new RankingVO(name, (int) count));
        }
        nameAllList.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));
        List<RankingVO> nameList = nameAllList.subList(0, Math.min(nameAllList.size(), 10));

        // 意向薪酬
        String salaryStr = list.stream().map(Student::getIntenSalary).filter(getIntenSalary -> !StrUtil.isBlank(getIntenSalary)).collect(Collectors.joining(","));
        String[] salaryArr = salaryStr.split(",");
        List<RankingVO> salaryAllList = new ArrayList<>();
        for (String salary : salaryArr) {
            long size = salaryAllList.stream().filter(d -> d.getName().equals(salary)).count();
            if (size > 0) {
                continue;
            }
            long count = Arrays.stream(salaryArr).filter(d -> d.equals(salary)).count();
            salaryAllList.add(new RankingVO(salary, (int) count));
        }
        salaryAllList.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));
        List<RankingVO> salaryList = salaryAllList.subList(0, Math.min(salaryAllList.size(), 3));

        Map<String, Object> intentionMap = new HashMap<>();
        intentionMap.put("addressList", addressList);
        intentionMap.put("industryList", industryList);
        intentionMap.put("nameList", nameList);
        intentionMap.put("salaryList", salaryList);


        // 产教融合
        // 产教融合单位数量
        Integer cooperativeCompanyCount = 98;
        // 产教融合学生数量
        Integer cooperativeStudentCount = 102;
        // 产教融合完成数量
        Integer cooperativeCompletedCount = 38;
        Map<String, Integer> cooperativeMap = new HashMap<>();
        cooperativeMap.put("cooperativeCompanyCount", cooperativeCompanyCount);
        cooperativeMap.put("cooperativeStudentCount", cooperativeStudentCount);
        cooperativeMap.put("cooperativeCompletedCount", cooperativeCompletedCount);

        // 百事打卡
        // 百事打卡学生人数
        Integer pepsiStudentCount = 5328;
        // 百事打卡完成项目
        Integer pepsiCompletedCount = 67;
        // 百事打卡完成项目排名前5
        List<RankingVO> pepsiList = new ArrayList<>();
        pepsiList.add(new RankingVO("做一份漂亮的简历", 3200));
        pepsiList.add(new RankingVO("职业生涯预约咨询", 2700));
        pepsiList.add(new RankingVO("完成职业测评", 2200));
        pepsiList.add(new RankingVO("加入创新团队", 1980));
        pepsiList.add(new RankingVO("每月听一次讲座", 980));
        Map<String, Object> pepsiMap = new HashMap<>();
        pepsiMap.put("pepsiStudentCount", pepsiStudentCount);
        pepsiMap.put("pepsiCompletedCount", pepsiCompletedCount);
        pepsiMap.put("pepsiList", pepsiList);

        Map<String, Object> map = new HashMap<>();
        map.put("intention", intentionMap);
        map.put("cooperative", cooperativeMap);
        map.put("pepsi", pepsiMap);
        return JsonResult.ok().setData(map);
    }

    @ApiOperation(value = "毕业去向饼图 就业率集合")
    @GetMapping("/big-view/student-sign-pie/sign-list")
    public JsonResult guidance(Integer year, String xl) {
        List<StudentSignRecord> list = studentSignRecordService.getStudentSignRateRecord(year, xl, null);
        return JsonResult.ok().setData(list);
    }
}
